package com.winit.schedule.job.tracker.repository.mysql.type.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.util.StringUtils;

import com.winit.schedule.core.model.JobID;
import com.winit.schedule.core.model.TaskID;

public class TaskIDTypeHandler implements TypeHandler<TaskID> {

    @Override
    public void setParameter(PreparedStatement ps, int i, TaskID parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getId());
    }

    @Override
    public TaskID getResult(ResultSet rs, String columnName) throws SQLException {
        String taskId = rs.getString(columnName);
        return string2TaskID(taskId);
    }

    @Override
    public TaskID getResult(ResultSet rs, int columnIndex) throws SQLException {
        String taskId = rs.getString(columnIndex);
        return string2TaskID(taskId);
    }

    @Override
    public TaskID getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String taskId = cs.getString(columnIndex);
        return string2TaskID(taskId);
    }

    private TaskID string2TaskID(String taskId) {
        String[] arr = StringUtils.delimitedListToStringArray(taskId, "$");
        if (arr.length == 3) {
            return new TaskID(new JobID(arr[0]), arr[1] + "$" + arr[2]);
        } else if (arr.length == 2) {
            return new TaskID(taskId);
        } else {
            return null;
        }
    }

}
